package com.invocation.attribute;

import org.springframework.security.access.prepost.PostInvocationAttribute;
import org.springframework.security.access.prepost.PreInvocationAttribute;
import org.springframework.security.access.prepost.PrePostInvocationAttributeFactory;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.common.Constant.ROLE_PREFIX;

public class RoleAttributeFactory implements PrePostInvocationAttributeFactory {


    public static final Pattern HAS_ROLE_PATTERN = Pattern.compile("hasRole\\('(.*)'\\)");

    @Override
    public PreInvocationAttribute createPreInvocationAttribute(String preFilterAttribute, String filterObject, String preAuthorizeAttribute) {
        if (preAuthorizeAttribute == null) {
            return null;
        }
        Matcher matcher = HAS_ROLE_PATTERN.matcher(preAuthorizeAttribute);
        boolean matches = matcher.matches();
        if (!matches) {
            return null;
        }

        String group = matcher.group(1);

        return new SimplePostInvocationAttribute(ROLE_PREFIX + group);
    }

    @Override
    public PostInvocationAttribute createPostInvocationAttribute(String postFilterAttribute, String postAuthorizeAttribute) {
        return null;
    }
}
